﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" :rules="formRules" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>单据信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
								<template #label>
									<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.BillCode" clearable class="width100" disabled placeholder="自动生成"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="备注" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remark" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>开除信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_PersonId_FormItem"
								prop="Entity.PersonId"
								:rules="[{ required: true, message: '开除员工为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="开除员工" tooltip="被开除的员工" />
								</template>
								<WtmPersonSelector
									v-model="stateData.vmModel.Entity.PersonId"
									@change="onPersonSelected"
									:prefill-person="{
										ID: stateData.vmModel.Entity.PersonId,
										Name: stateData.vmModel.Entity.Name,
										StaffNo: stateData.vmModel.Entity.StaffNo,
									}"
								/>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
								<template #label>
									<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.StaffNo" clearable class="width100" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
								<template #label>
									<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_DismissDate_FormItem"
								prop="Entity.DismissDate"
								:rules="[{ required: true, message: '开除日期为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="开除日期" tooltip="开除发生日期" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.DismissDate" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_ResignType_FormItem"
								prop="Entity.ResignType"
								:rules="[{ required: true, message: '开除类型为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="开除类型" tooltip="开除类型" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.ResignType" clearable class="width100">
									<el-option key="试用期不合格" value="试用期不合格" label="试用期不合格"></el-option>
									<el-option key="严重违纪" value="严重违纪" label="严重违纪"></el-option>
									<el-option key="严重失职或舞弊" value="严重失职或舞弊" label="严重失职或舞弊"></el-option>
									<el-option key="兼岗影响履职且拒不改正" value="兼岗影响履职且拒不改正" label="兼岗影响履职且拒不改正"></el-option>
									<el-option key="欺诈入职或合同无效" value="欺诈入职或合同无效" label="欺诈入职或合同无效"></el-option>
									<el-option key="刑事责任" value="刑事责任" label="刑事责任"></el-option>
									<el-option key="违反保密或竞业" value="违反保密或竞业" label="违反保密或竞业"></el-option>
									<el-option key="其他" value="其他" label="其他"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_Describe_FormItem"
								prop="Entity.Describe"
								:rules="[{ required: true, message: '开除说明为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="开除说明" tooltip="开除原因或说明" />
								</template>
								<el-input type="textarea" v-model="stateData.vmModel.Entity.Describe" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="SupportingDocumentId_FormItem" prop="Entity.SupportingDocumentId">
								<template #label>
									<WtmLabelTooltip label="证明文件" tooltip="上传辞退证明文件" />
								</template>
								<wtm-upload-file
									v-model="stateData.vmModel.Entity.SupportingDocumentId"
									:allowed-types="['application/pdf', 'image/jpeg', 'image/png', 'image/jpg']"
									clearable
									:multi="false"
								></wtm-upload-file>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>工作信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmOrgSelector v-model="stateData.vmModel.Entity.OrgId" label="公司" :auth="false" :disabled="true" placeholder="选取人员后带入" />
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmDeptSelector v-model:model-value="stateData.vmModel.Entity.GroupId" label="所属部门" :auth="false" :disabled="true" />
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.edit;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, nextTick, computed, type ComponentInternalInstance } from 'vue';
import { SysHrDismissRequestBillApi as api } from '/@/views/hr/syshrdismissrequestbill/api';
import other from '/@/utils/other';
import { useRouter } from 'vue-router';
import { ISysHrDismissRequestBillVm } from '/@/views/hr/syshrdismissrequestbill/api/interface';
import { IViewModel, ISysSelectType } from '/@/types/common';

// 常量定义
const BILL_STATUS = {
	DRAFT: '草稿',
	IN_AUDIT: '审核中',
} as const;

const WORKFLOW_STATUS = {
	PENDING: '待提交',
	SUBMITTING: '提交中',
	IN_AUDIT: '审核中',
} as const;

const RESIGN_TYPE_OPTIONS = [
	{ value: '主动离职', label: '主动离职' },
	{ value: '被动离职', label: '被动离职' },
	{ value: '退休', label: '退休' },
] as const;

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	AGREE: '同意',
	REJECT: '取消',
	CLOSE: '关闭',
} as const;

const ACTIONS = {
	AGREE: '同意',
	REJECT: '拒绝',
} as const;

const API_ENDPOINTS = {
	PERSONS: '/api/SysHrDismissRequestBill/GetSysPersons',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();

// 表单验证规则
const formRules = {
	'Entity.StaffNo': [{ required: true, message: '请输入员工工号', trigger: 'blur' }],
	'Entity.Name': [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
	'Entity.DismissDate': [{ required: true, message: '请选择开除日期', trigger: 'change' }],
	'Entity.ResignType': [{ required: true, message: '请选择离职类型', trigger: 'change' }],
	'Entity.GroupId': [{ required: true, message: '请选择所属部门', trigger: 'change' }],
};

// 初始化表单数据
const stateData = reactive<IViewModel<ISysHrDismissRequestBillVm>>({
	vmModel: {
		Entity: {
			ID: null,
			PersonId: null,
			DismissDate: null,
			ResignType: null,
			Describe: null,
			Approver: null,
			ApprovalTime: null,
			OrgId: null,
			GroupId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
			// 用于回显
			StaffNo: '',
			Name: '',
			SupportingDocumentId: [],
		},
		ActionName: null,
		IsMyApprove: null,
		Remark: null,
	},
	AllSysPersons: [] as ISysSelectType[],
});

// 计算属性
const isInAudit = computed(() => stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.IN_AUDIT);
const canSubmit = computed(() => stateData.vmModel.Entity.BillStatus === BILL_STATUS.DRAFT);
const canApprove = computed(() => !!stateData.vmModel.IsMyApprove);

// 统一的成功处理函数
const handleSuccess = (isSubmit = false) => {
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
		emit('refresh');
		emit('closeDialog');
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
		emit('refresh');
	}
	loading.value = false;
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的API请求处理函数
const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			apiCall()
				.then(() => handleSuccess(isSubmit))
				.catch(handleError);
		}
	});
};

// 公共的审批处理函数
const handleApproval = (actionName: string) => {
	stateData.vmModel.ActionName = actionName;
	loading.value = true;
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			api()
				.approve(stateData.vmModel, '')
				.then(() => handleSuccess(true))
				.catch(handleError);
		} else {
			loading.value = false;
		}
	});
};

// 取消
const onClose = () => {
	emit('closeDialog');
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {},
		false
	);
};

// 提交
const onSubmit = () => {
	if (!stateData.vmModel.Entity.WorkflowStatus || stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.PENDING) {
		stateData.vmModel.Entity.WorkflowStatus = WORKFLOW_STATUS.SUBMITTING;
	}
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {},
		true
	);
};

// 同意
const onAgree = () => {
	handleApproval(ACTIONS.AGREE);
};

// 拒绝
const onDeny = () => {
	handleApproval(ACTIONS.REJECT);
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	const routeId = useRouter().currentRoute.value.query.id;

	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	} else if (routeId) {
		stateData.vmModel.Entity.ID = routeId as any;
	}
};

// 加载页面数据（含回显）
const loadPageData = async () => {
	const [persons, entityData] = await Promise.allSettled([
		other.getSelectList(API_ENDPOINTS.PERSONS, [], false),
		api().get(stateData.vmModel.Entity.ID ?? ''),
	]);

	// 处理成功的结果
	if (persons.status === 'fulfilled') stateData.AllSysPersons = persons.value;
	if (entityData.status === 'fulfilled') {
		other.setValue(stateData.vmModel, entityData.value);
		// 根据 PersonId 加载人员信息以回显工号与姓名
		const pid = stateData.vmModel.Entity.PersonId as any;
		if (pid) {
			try {
				// 复用后端 /api/SysPerson/{id} 接口
				const resp = await (await import('/@/views/person/sysperson/api')).SysPersonApi().get(pid);
				const p = resp?.data?.Entity || resp?.data;
				if (p) {
					stateData.vmModel.Entity.StaffNo = p.StaffNo || '';
					stateData.vmModel.Entity.Name = p.Name || '';
				}
			} catch {}
		}
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: undefined,
			onClick: onSave,
			visible: !isInAudit.value,
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			confirm: '提交单据以后无法修改，是否确认提交?',
			type: 'primary',
			onClick: onSubmit,
			visible: canSubmit.value && !isInAudit.value,
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onAgree,
			visible: isInAudit.value && canApprove.value,
		},
		{
			text: BUTTON_TEXTS.REJECT,
			type: 'danger',
			onClick: onDeny,
			visible: isInAudit.value && canApprove.value,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};

// 人员选择变化处理（用于同步工号与姓名回显）
const onPersonSelected = (value: any, person: any) => {
	if (person) {
		stateData.vmModel.Entity.StaffNo = person.StaffNo || '';
		stateData.vmModel.Entity.Name = person.Name || '';
		stateData.vmModel.Entity.OrgId = person.OrgId || '';
		stateData.vmModel.Entity.GroupId = person.GroupId || '';
	} else {
		stateData.vmModel.Entity.StaffNo = '';
		stateData.vmModel.Entity.Name = '';
		stateData.vmModel.Entity.OrgId = '';
		stateData.vmModel.Entity.GroupId = '';
	}
};
</script>
